﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Reflection;
using System.IO;
using System.Net;
using Newtonsoft.Json;
using System.Text.RegularExpressions;
namespace UcAsp.Net.Extract
{
    public partial class FrmBase : Form
    {
        List<Assembly> obj = new List<Assembly>();
        List<FileInfo> FileInfo = new List<FileInfo>();
        public FrmBase()
        {
            InitializeComponent();

        }

        private void FrmBase_Load(object sender, EventArgs e)
        {


            FileInfo[] file = new DirectoryInfo(AppDomain.CurrentDomain.BaseDirectory + @"\Plug\").GetFiles();
            int i = 0;
            foreach (FileInfo info in file)
            {

                if (info.Extension.Equals(".dll"))
                {
                    Assembly _obj = Assembly.LoadFrom(info.FullName);
                    Type type = _obj.GetType(info.Name.Replace(info.Extension, "") + ".UcAspControl");
                    Type settype = _obj.GetType(info.Name.Replace(info.Extension, "") + ".UcAspSettingControl");

                    if (settype != null)
                    {
                        Button btn = new Button();

                        btn.Text = info.Name.Replace(info.Extension, "");
                        foreach (Attribute attr in Attribute.GetCustomAttributes(_obj))
                        {
                            if (attr.GetType() == typeof(AssemblyTitleAttribute))
                            {

                                btn.Text = ((AssemblyTitleAttribute)attr).Title + "设置";
                            }
                        }
                        btn.Width = 150;
                        btn.Tag = info.Name.Replace(info.Extension, "");
                        leftMenu.Controls.Add(btn);
                        btn.TabIndex = i;
                        btn.Click += new EventHandler(setbtn_Click);
                    }

                    if (type != null)
                    {
                        Button btn = new Button();

                        btn.Text = info.Name.Replace(info.Extension, "");
                        foreach (Attribute attr in Attribute.GetCustomAttributes(_obj))
                        {
                            if (attr.GetType() == typeof(AssemblyTitleAttribute))
                            {
                                btn.Text = "同步";
                            }
                        }
                        btn.Width = 50;
                        btn.Tag = info.Name.Replace(info.Extension, "");
                        leftMenu.Controls.Add(btn);
                        btn.TabIndex = i;
                        btn.Click += new EventHandler(btn_Click);


                    }
                    obj.Add(_obj);
                    FileInfo.Add(info);
                    i++;
                }

            }

        }
        void setbtn_Click(object sender, EventArgs e)
        {
            Button btn = (Button)sender;
            Type type = obj[btn.TabIndex].GetType(btn.Tag.ToString() + ".UcAspSettingControl");
            Object o = Activator.CreateInstance(type);

            foreach (Control ctrl in palControl.Controls)
            {
                palControl.Controls.Remove(ctrl);
            }
            palControl.Controls.Add((Control)o);
        }
        void btn_Click(object sender, EventArgs e)
        {
            Button btn = (Button)sender;
            Type type = obj[btn.TabIndex].GetType(btn.Tag.ToString() + ".UcAspControl");
            Object o = Activator.CreateInstance(type);
            foreach (Control ctrl in palControl.Controls)
            {
                try
                {
                    UcAsp.Net.Interface.IExtract extsave = (UcAsp.Net.Interface.IExtract)ctrl;
                    extsave.Save -= new EventHandler(extracet_Save);
                    extsave.SavePage -= new EventHandler(extracet_SavePage);
                }
                catch
                { }
                palControl.Controls.Remove(ctrl);
            }
            UcAsp.Net.Interface.IExtract extracet = (UcAsp.Net.Interface.IExtract)o;
            extracet.Security = "d4ae69128c0552305c8c23f210d158d2";
            palControl.Controls.Add((Control)extracet);
            
           
            extracet.Save += new EventHandler(extracet_Save);
            extracet.SavePage += new EventHandler(extracet_SavePage);
        }
        #region 保存分页
        void extracet_SavePage(object sender, EventArgs e)
        {
            UcAsp.Net.Interface.IExtract o = (UcAsp.Net.Interface.IExtract)sender;
            #region
            Model.Articles art = new Model.Articles
            {
                ID = o.ID,
                AddDatetime = o.AddDatetime,
                ArticleContent = o.ArticleContent,
                CategorieID = o.CategorieID,
                Date1 = o.Date1,
                Date2 = o.Date2,
                Date3 = o.Date3,
                Date4 = o.Date4,
                Date5 = o.Date5,
                Date6 = o.Date6,
                Date7 = o.Date7,
                Date8 = o.Date8,
                Description = o.Description,
                Float1 = o.Float1,
                Float2 = o.Float2,
                Float3 = o.Float3,
                Float4 = o.Float4,
                Float5 = o.Float5,
                Hot = o.Hot,
                IconUrl = o.IconUrl,
                Int1 = o.Int1,
                Int2 = o.Int2,
                Int3 = o.Int3,
                Int4 = o.Int4,
                Int5 = o.Int5,
                IsRecommend = o.IsRecommend,
                IsRelease = o.IsRelease,
                MetaDescrition = o.MetaDescrition,
                MetaKeyword = o.MetaKeyword,
                Note1 = o.Note1,
                Note2 = o.Note2,
                Note3 = o.Note3,
                Note4 = o.Note4,
                Note5 = o.Note5,
                Note6 = o.Note6,
                Note7 = o.Note7,
                Note8 = o.Note8,
                Note9 = o.Note9,
                Rate = o.Rate,
                ShowPath = o.ShowPath,
                Tag = o.Tag,
                Title = o.Title,
                UserID = o.UserID,
                ViewsTemp = o.ViewsTemp,
                PageCount = o.PageCount
            };
            #endregion

            Type type = art.GetType();
            System.Reflection.PropertyInfo[] prinfo = type.GetProperties();

            
            string secrity = UcAsp.Net.Comm.Encrypt.EncodeEncrypt("d4ae69128c0552305c8c23f210d158d2");

            Dictionary<string, string> param = new Dictionary<string, string>();

            param.Add("PageID", art.Int1.ToString());
            param.Add("ArticlesID", art.ID.ToString());
            param.Add("Title", art.Title.ToString());

            string code = PostString("http://www.hzspace.com/admin/CheckArticlesPage?Security=" + secrity + "", param);
            JsonSerializer serializer = new JsonSerializer();

            JsonReader messagejon = new JsonTextReader(new StringReader(code));
            Model.Message message = (Model.Message)serializer.Deserialize(messagejon, typeof(Model.Message));
            if (!message.Result)
            {
                if (o.Image != null)
                {
                    art.ArticleContent = ReplaceIMG(o.ArticleContent, o.Image);

                }
                if (o.IconUrl != null) {
                    IDictionary<object, object> dic = new Dictionary<object, object>();
                    byte[] img=GetImage(o.IconUrl);
                    if (img != null)
                    {
                        art.IconUrl = HttpPost("http://www.hzspace.com/UploadFile.ashx?Security=" + secrity + "", dic, img);
                        param.Add("IconUrl", art.IconUrl.ToString());
                    }
                }
                param.Add("CategoriesID", art.CategorieID.ToString());

                param.Add("ArticlesContent", art.ArticleContent.ToString());
                param.Add("AddDateTime", art.AddDatetime.ToString());

                serializer = new JsonSerializer();
                code = PostString("http://www.hzspace.com/admin/SaveArticlesPage?Security=" + secrity + "", param);
                messagejon = new JsonTextReader(new StringReader(code));
                message = (Model.Message)serializer.Deserialize(messagejon, typeof(Model.Message));
            }
        }
        #endregion
        #region 保存内容
        void extracet_Save(object sender, EventArgs e)
        {

            UcAsp.Net.Interface.IExtract o = (UcAsp.Net.Interface.IExtract)sender;
            #region
            Model.Articles art = new Model.Articles
            {
                ID = o.ID,
                AddDatetime = o.AddDatetime,
                ArticleContent = o.ArticleContent,
                CategorieID = o.CategorieID,
                Date1 = o.Date1,
                Date2 = o.Date2,
                Date3 = o.Date3,
                Date4 = o.Date4,
                Date5 = o.Date5,
                Date6 = o.Date6,
                Date7 = o.Date7,
                Date8 = o.Date8,
                Description = o.Description,
                Float1 = o.Float1,
                Float2 = o.Float2,
                Float3 = o.Float3,
                Float4 = o.Float4,
                Float5 = o.Float5,
                Hot = o.Hot,
                IconUrl = o.IconUrl,
                Int1 = o.Int1,
                Int2 = o.Int2,
                Int3 = o.Int3,
                Int4 = o.Int4,
                Int5 = o.Int5,
                IsRecommend = o.IsRecommend,
                IsRelease = o.IsRelease,
                MetaDescrition = o.MetaDescrition,
                MetaKeyword = o.MetaKeyword,
                Note1 = o.Note1,
                Note2 = o.Note2,
                Note3 = o.Note3,
                Note4 = o.Note4,
                Note5 = o.Note5,
                Note6 = o.Note6,
                Note7 = o.Note7,
                Note8 = o.Note8,
                Note9 = o.Note9,
                Rate = o.Rate,
                ShowPath = o.ShowPath,
                Tag = o.Tag,
                Title = o.Title,
                UserID = o.UserID,
                ViewsTemp = o.ViewsTemp,
                PageCount = o.PageCount
            };
            #endregion





            Type type = art.GetType();
            System.Reflection.PropertyInfo[] prinfo = type.GetProperties();

            Dictionary<string, string> param = new Dictionary<string, string>();
            param.Add("Title", o.Title);
            

            string secrity = UcAsp.Net.Comm.Encrypt.EncodeEncrypt("d4ae69128c0552305c8c23f210d158d2");
            string code = PostString("http://www.hzspace.com/admin/CheckArtices?Security=" + secrity + "", param);
            JsonSerializer serializer = new JsonSerializer();

            JsonReader messagejon = new JsonTextReader(new StringReader(code));
            Model.Message message = (Model.Message)serializer.Deserialize(messagejon, typeof(Model.Message));

            if (!message.Result)
            {
                if (o.Image != null)
                {
                    art.ArticleContent = ReplaceIMG(o.ArticleContent, o.Image);

                }
                if (o.IconUrl != null)
                {
                    IDictionary<object, object> dic = new Dictionary<object, object>();
                    byte[] img = GetImage(o.IconUrl);
                    if (img != null)
                    {
                        art.IconUrl = HttpPost("http://www.hzspace.com/UploadFile.ashx?Security=" + secrity + "", dic, img);
                    }
                }
                param.Clear();
                for (int i = 0; i < prinfo.Length; i++)
                {
                    if (prinfo[i].GetValue(art, null) != null)
                    {
                        param.Add(prinfo[i].Name, prinfo[i].GetValue(art, null).ToString());
                    }
                }
                code = PostString("http://www.hzspace.com/admin/SaveArtices?Security=" + secrity + "", param);
                serializer = new JsonSerializer();

                messagejon = new JsonTextReader(new StringReader(code));
                message = (Model.Message)serializer.Deserialize(messagejon, typeof(Model.Message));
                o.ID = int.Parse(message.Note1);
            }
            else {
                o.ID = int.Parse(message.Note1);
            }

        }
        #endregion
        private string ReplaceIMG(string content, string code)
        {
            string secrity = UcAsp.Net.Comm.Encrypt.EncodeEncrypt("d4ae69128c0552305c8c23f210d158d2");
            RegexOptions options = RegexOptions.None;
            Regex regex = new Regex(code, options);
            MatchCollection matches = regex.Matches(content);
            IDictionary<object, object> param = new Dictionary<object, object>();
            for (int j = 0; j < matches.Count; j++)
            {
                string url=matches[j].Groups["img"].Value;
                if (url.IndexOf("data:image/jpg;base64") > 0)
                { }
                else
                {
                    byte[] img = GetImage(url);
                    if (img != null)
                    {
                        string message = HttpPost("http://www.hzspace.com/UploadFile.ashx?Security=" + secrity + "", param, img);
                        content = content.ToLower().Replace(matches[j].Groups["img"].Value.ToLower(), message);
                    }
                    else
                    {
                        content = content.ToLower().Replace(matches[j].Groups["img"].Value.ToLower(), "");
                    }
                }
                
                // MessageBox.Show(message);
            }
            return content;

        }
        private string PostString(string url, Dictionary<string, string> param)
        {
            string result = string.Empty;
            HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
            req.Method = "POST";
            req.KeepAlive = true;
            req.UserAgent = "UcAspApp2.0";
            req.Timeout = 300000;
            req.ContentType = "application/x-www-form-urlencoded;charset=utf-8";

            byte[] postData = Encoding.UTF8.GetBytes(PostData(param));
            Stream reqStream = req.GetRequestStream();
            reqStream.Write(postData, 0, postData.Length);
            reqStream.Close();

            HttpWebResponse rsp = (HttpWebResponse)req.GetResponse();
            Encoding encoding = Encoding.GetEncoding(rsp.CharacterSet);

            Stream stream = null;
            StreamReader reader = null;

            stream = rsp.GetResponseStream();
            reader = new StreamReader(stream, encoding);

            result = reader.ReadToEnd();

            if (reader != null) reader.Close();
            if (stream != null) stream.Close();
            if (rsp != null) rsp.Close();
            return result;
        }
        protected static string PostData(IDictionary<string, string> parameters)
        {
            StringBuilder postData = new StringBuilder();
            bool hasParam = false;

            IEnumerator<KeyValuePair<string, string>> dem = parameters.GetEnumerator();
            while (dem.MoveNext())
            {
                string name = dem.Current.Key;
                string value = dem.Current.Value;
                // 忽略参数名或参数值为空的参数
                if (!string.IsNullOrEmpty(name) && !string.IsNullOrEmpty(value))
                {
                    if (hasParam)
                    {
                        postData.Append("&");
                    }

                    postData.Append(name);
                    postData.Append("=");
                    postData.Append(Uri.EscapeDataString(value));
                    hasParam = true;
                }
            }

            return postData.ToString();
        }
        public static byte[] GetImage(string url)
        {
            try
            {
                WebClient web = new WebClient();
                web.Headers.Add("User-Agent", "Mozilla/5.0 (Windows NT 6.2; rv:24.0) Gecko/20100101 Firefox/24.0");
                web.Headers.Add("Referer", "http://www.vogue.com.cn/");
                byte[] webbyte = web.DownloadData(url);
                return webbyte;
            }
            catch { 
                return null;
            }
        }
        #region Post With Pic
        /// <summary>
        /// HTTP POST方式请求数据(带图片)
        /// </summary>
        /// <param name="url">URL</param>        
        /// <param name="param">POST的数据</param>
        /// <param name="fileByte">图片</param>
        /// <returns></returns>
        public static string HttpPost(string url, IDictionary<object, object> param, byte[] fileByte)
        {
            string boundary = "---------------------------" + DateTime.Now.Ticks.ToString("x");
            byte[] boundarybytes = System.Text.Encoding.ASCII.GetBytes("\r\n--" + boundary + "\r\n");

            HttpWebRequest wr = (HttpWebRequest)WebRequest.Create(url);
            wr.ContentType = "multipart/form-data; boundary=" + boundary;
            wr.Method = "POST";
            wr.KeepAlive = true;
            wr.Credentials = System.Net.CredentialCache.DefaultCredentials;

            Stream rs = wr.GetRequestStream();
            string responseStr = null;

            string formdataTemplate = "Content-Disposition: form-data; name=\"{0}\"\r\n\r\n{1}";
            foreach (string key in param.Keys)
            {
                rs.Write(boundarybytes, 0, boundarybytes.Length);
                string formitem = string.Format(formdataTemplate, key, param[key]);
                byte[] formitembytes = System.Text.Encoding.UTF8.GetBytes(formitem);
                rs.Write(formitembytes, 0, formitembytes.Length);
            }
            rs.Write(boundarybytes, 0, boundarybytes.Length);

            string headerTemplate = "Content-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"\r\nContent-Type: {2}\r\n\r\n";
            string header = string.Format(headerTemplate, "pic", "show.jpg", "text/plain");//image/jpeg
            byte[] headerbytes = System.Text.Encoding.UTF8.GetBytes(header);
            rs.Write(headerbytes, 0, headerbytes.Length);

            rs.Write(fileByte, 0, fileByte.Length);

            byte[] trailer = System.Text.Encoding.ASCII.GetBytes("\r\n--" + boundary + "--\r\n");
            rs.Write(trailer, 0, trailer.Length);
            rs.Close();

            WebResponse wresp = null;
            try
            {
                wresp = wr.GetResponse();
                Stream stream2 = wresp.GetResponseStream();
                StreamReader reader2 = new StreamReader(stream2);
                responseStr = reader2.ReadToEnd();

            }
            catch (Exception ex)
            {

                if (wresp != null)
                {
                    wresp.Close();
                    wresp = null;
                }
            }
            finally
            {
                wr = null;
            }
            return responseStr;
        }
        #endregion

    }
}
